﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Serialization;
using Microsoft.SharePoint;
using System.Linq;
using System.Reflection;

namespace SPMetadataSecurity.MetadataSecurityConfigurationWebPart
{
    public partial class MetadataSecurityConfigurationWebPartUserControl : UserControl
    {
        private SPContentType _selectedContentType;
        public SPContentType SelectedContentType
        {
            get
            {
                _selectedContentType = null;
                SPWeb rootWeb = SPContext.Current.Site.RootWeb;
                if (!string.IsNullOrEmpty(ContentTypeList.SelectedValue))
                {
                    _selectedContentType = rootWeb.ContentTypes[new SPContentTypeId(ContentTypeList.SelectedValue)];
                }
                return _selectedContentType;
            }
        }

        private MetadataSecuirtyConfiguration _savedSecurityConfiguration;

        public MetadataSecuirtyConfiguration SavedSecurityConfiguration
        {
            get
            {
                _savedSecurityConfiguration = null;
                var selectedContentType = SelectedContentType;
                if (selectedContentType != null)
                {
                    SPWeb rootWeb = SPContext.Current.Site.RootWeb;
                    string xml = rootWeb.GetProperty(selectedContentType.Name + "_Metadata_Security") as string;
                    if (!string.IsNullOrEmpty(xml))
                    {
                        XmlSerializer serializer = new XmlSerializer(typeof(MetadataSecuirtyConfiguration));
                        StringReader reader = new StringReader(xml);
                        _savedSecurityConfiguration = serializer.Deserialize(reader) as MetadataSecuirtyConfiguration;
                    }
                    else
                    {
                        _savedSecurityConfiguration = new MetadataSecuirtyConfiguration() { ConfigurationRules = new List<Rule>() };
                    }
                }
                return _savedSecurityConfiguration;
            }
            set
            {
                var selectedContentType = SelectedContentType;
                _savedSecurityConfiguration = value;
                SPWeb rootWeb = SPContext.Current.Site.RootWeb;
                XmlSerializer serializer = new XmlSerializer(typeof(MetadataSecuirtyConfiguration));
                StringWriter writer = new StringWriter();
                serializer.Serialize(writer, _savedSecurityConfiguration);
                rootWeb.DeleteProperty(selectedContentType.Name + "_Metadata_Security");
                rootWeb.AddProperty(selectedContentType.Name + "_Metadata_Security", writer.ToString());
                rootWeb.Update();
            }
        }

        private MetadataSecuirtyConfiguration _currentSecurityConfiguration;
        public MetadataSecuirtyConfiguration CurrentSecurityConfiguration
        {
            get
            {
                _currentSecurityConfiguration = null;
                if (ViewState["MetadataSecuirtyConfiguration"] != null)
                {
                    _currentSecurityConfiguration = ViewState["MetadataSecuirtyConfiguration"] as MetadataSecuirtyConfiguration;
                }
                else
                {
                    _currentSecurityConfiguration = SavedSecurityConfiguration;
                }
                ViewState["MetadataSecuirtyConfiguration"] = _currentSecurityConfiguration;
                return _currentSecurityConfiguration;
            }
            set
            {
                ViewState["MetadataSecuirtyConfiguration"] = value;
            }
        }

        #region Control Events

        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                if (!Page.IsPostBack)
                {
                    InitializeContentTypeList();
                    InitializeMetadataColumnList();
                    InitializeGroupsList();
                    InitializePermissionLevelsList();
                }
                AddMetadataValueControl();
                MessageLabel.Text = string.Empty;
                ErrorMessageLabel.Text = string.Empty;
                if (SelectedContentType == null)
                {
                    RulesGridViewWrapper.Visible = false;
                    AddNewRuleButton.Visible = false;
                    AddNewRuleSection.Visible = false;
                }
                else
                {
                    ShowExistingRulesForContentType();
                    RulesGridViewWrapper.Visible = true;
                    AddNewRuleButton.Visible = true;
                }
            }
            catch (Exception ex)
            {
                SetMessage(ex.Message + Environment.NewLine + ex.StackTrace, true);
            }
        }

        private void ShowExistingRulesForContentType()
        {
            MetadataSecuirtyConfiguration config = SavedSecurityConfiguration;
            if (config != null && config.ConfigurationRules != null
                && config.ConfigurationRules.Count > 0)
            {
                var rules = from r in config.ConfigurationRules
                            orderby r.SequenceNumber ascending
                            select r;
                RulesGridView.DataSource = rules;
                RulesGridView.DataBind();
            }
            else
            {
                RulesGridView.DataSource = null;
                RulesGridView.DataBind();
            }
        }

        protected void ContentTypeList_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                InitializeMetadataColumnList();
                AddNewRuleSection.Visible = false;
                CurrentSecurityConfiguration = null;
            }
            catch (Exception ex)
            {
                SetMessage(ex.Message + Environment.NewLine + ex.StackTrace, true);
            }
        }

        protected void MetadataColumnList_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                AddMetadataValueControl();
            }
            catch (Exception ex)
            {
                SetMessage(ex.Message + Environment.NewLine + ex.StackTrace, true);
            }
        }
        protected void AddConditionButton_Click(object sender, EventArgs e)
        {
            try
            {
                MetadataSecuirtyConfiguration config = CurrentSecurityConfiguration;
                Rule rule = null;
                bool isNewRule = false;
                if (config.ConfigurationRules.Count > 0 && config.ConfigurationRules.Count == int.Parse(RuleSequenceNumberTextBox.Text))
                {
                    rule = config.ConfigurationRules.First(x => x.SequenceNumber == int.Parse(RuleSequenceNumberTextBox.Text));
                }
                else
                {
                    isNewRule = true;
                    rule = new Rule();
                }
                rule.SequenceNumber = int.Parse(RuleSequenceNumberTextBox.Text);

                if (rule.Conditions == null)
                {
                    rule.Conditions = new List<Condition>();
                }
                ControlHelper helper = new ControlHelper();
                var selectedContentType = SelectedContentType;
                SPField metadataColumn = selectedContentType.Fields[new Guid(MetadataColumnList.SelectedValue)];
                Control control = MetadataValueDiv.FindControl("MetadataValueControl" + metadataColumn.Type.ToString());

                Condition condition = new Condition()
                {
                    Id = rule.Conditions.Count + 1,
                    MetadataColumnName = MetadataColumnList.SelectedItem.Text,
                    MetadataColumnId = MetadataColumnList.SelectedValue,
                    Operator = OperatorList.SelectedValue,
                    MetadataValue = helper.GetControlValue(control, metadataColumn.Type)
                };
                rule.Conditions.Add(condition);
                if (isNewRule)
                {
                    config.ConfigurationRules.Add(rule);
                }
                CurrentSecurityConfiguration = config;
                AppliedConditionsGridView.DataSource = rule.Conditions;
                AppliedConditionsGridView.DataBind();                
            }
            catch (Exception ex)
            {
                SetMessage(ex.Message + Environment.NewLine + ex.StackTrace, true);
            }
        }

        protected void AddPermissionButton_Click(object sender, EventArgs e)
        {
            try
            {
                MetadataSecuirtyConfiguration config = CurrentSecurityConfiguration;
                Rule rule = null;
                bool isNewRule = false;
                if (config.ConfigurationRules.Count > 0 && config.ConfigurationRules.Count == int.Parse(RuleSequenceNumberTextBox.Text))
                {
                    rule = config.ConfigurationRules.First(x => x.SequenceNumber == int.Parse(RuleSequenceNumberTextBox.Text));
                }
                else
                {
                    isNewRule = true;
                    rule = new Rule();
                }
                rule.SequenceNumber = int.Parse(RuleSequenceNumberTextBox.Text);
                PermissionAction action = null;
                if (rule.Action == null)
                {
                    action = new PermissionAction();
                }
                else
                {
                    action = rule.Action;
                }
                if (action.GroupPermissions == null)
                {
                    action.GroupPermissions = new List<GroupPermission>();
                }
                GroupPermission gp = new GroupPermission()
                {
                    Id = action.GroupPermissions.Count + 1,
                    GroupName = GroupList.SelectedItem.Text,
                    GroupId = GroupList.SelectedValue,
                    PermissionLevelName = PermissionLevelList.SelectedItem.Text,
                    PermissionLevelId = PermissionLevelList.SelectedValue
                };
                action.GroupPermissions.Add(gp);
                rule.Action = action;
                if (isNewRule)
                {
                    config.ConfigurationRules.Add(rule);
                }
                CurrentSecurityConfiguration = config;                
                AppliedPermissionsGridView.DataSource = rule.Action.GroupPermissions;
                AppliedPermissionsGridView.DataBind();
            }
            catch (Exception ex)
            {
                SetMessage(ex.Message + Environment.NewLine + ex.StackTrace, true);
            }
        }

        protected void SaveRuleButton_Click(object sender, EventArgs e)
        {
            try
            {
                SPContentType selectedContentType = SelectedContentType;
                if (selectedContentType != null)
                {
                    MetadataSecuirtyConfiguration config = CurrentSecurityConfiguration;
                    if (config != null)
                    {
                        Rule rule = config.ConfigurationRules.First(x => x.SequenceNumber == int.Parse(RuleSequenceNumberTextBox.Text));
                        rule.SequenceNumber = int.Parse(RuleSequenceNumberTextBox.Text.Trim());
                        rule.Name = RuleNameTextBox.Text.Trim();
                        rule.StopIfRuleApplies = StopProcessingIfRuleAppliesCheckBox.Checked;
                        PermissionAction action = rule.Action;
                        action.StopInheritingPermission = StopInheritingPermissionsCheckBox.Checked;
                        action.RemoveInheritedPermissions = RemoveInheritedPermissionsCheckBox.Checked;
                        action.UpdateExistingItems = UpdateExistingItemsCheckBox.Checked;
                        CurrentSecurityConfiguration = config;
                        SavedSecurityConfiguration = config;
                        RemoveEventReceiverFromContentType(selectedContentType);
                        AddEventReceiverToContentType(selectedContentType);
                        ShowExistingRulesForContentType();
                        ShowAddNewRuleForm();
                        SetMessage("Rules Saved Succefully.", false);
                    }
                }
            }
            catch (Exception ex)
            {
                SetMessage(ex.Message + Environment.NewLine + ex.StackTrace, true);
            }
        }

        protected void RemoveRulesButton_Click(object sender, EventArgs e)
        {
            try
            {
                SPContentType selectedContentType = SelectedContentType;
                if (selectedContentType != null)
                {
                    SPWeb rootWeb = SPContext.Current.Site.RootWeb;
                    rootWeb.DeleteProperty(selectedContentType.Name + "_Metadata_Security");
                    rootWeb.Update();
                    CurrentSecurityConfiguration = null;
                    ShowExistingRulesForContentType();
                    SetMessage("Rule removed from the content type", false);
                    //InitializeAppliedRulesAndPermissions();
                }
            }
            catch (Exception ex)
            {
                SetMessage(ex.Message + Environment.NewLine + ex.StackTrace, true);
            }
        }

        protected void AddNewRuleButton_Click(object sender, EventArgs e)
        {
            try
            {
                ShowAddNewRuleForm();
            }
            catch (Exception ex)
            {
                SetMessage(ex.Message + Environment.NewLine + ex.StackTrace, true);
            }
        }

        protected void CancelButton_Click(object sender, EventArgs e)
        {
            ShowAddNewRuleForm();
            AddNewRuleSection.Visible = false;
        }

        protected void RulesGridView_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            try
            {
                int ruleNumber = Convert.ToInt32(e.CommandArgument) + 1;
                if (e.CommandName == "EditRule")
                {
                    var config = SavedSecurityConfiguration;
                    if (config != null && config.ConfigurationRules != null)
                    {
                        Rule rule = config.ConfigurationRules.FirstOrDefault(x => x.SequenceNumber == ruleNumber);
                        if (rule != null)
                        {
                            ShowEditRuleForm(rule);
                        }
                    }
                }
                else if (e.CommandName == "DeleteRule")
                {
                    var config = SavedSecurityConfiguration;
                    if (config != null && config.ConfigurationRules != null)
                    {
                        Rule rule = config.ConfigurationRules.FirstOrDefault(x => x.SequenceNumber == ruleNumber);
                        if (rule != null)
                        {
                            config.ConfigurationRules.Remove(rule);
                        }
                        var rules = from r in config.ConfigurationRules
                                    orderby r.SequenceNumber descending
                                    select r;
                        int i = 1;
                        foreach (Rule r in rules)
                        {
                            r.SequenceNumber = i;
                            i++;
                        }
                        SavedSecurityConfiguration = config;
                        ShowExistingRulesForContentType();
                        RuleSequenceNumberTextBox.Text = (config.ConfigurationRules.Count + 1).ToString();
                    }                    
                }
            }
            catch (Exception ex)
            {
                SetMessage(ex.Message + Environment.NewLine + ex.StackTrace, true);
            }
        }

        protected void AppliedConditionsGridView_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            try
            {
                int ruleNumber = Convert.ToInt32(RuleSequenceNumberTextBox.Text);
                if (e.CommandName == "EditCondition")
                {
                    var config = CurrentSecurityConfiguration;
                    if (config != null && config.ConfigurationRules != null)
                    {
                        Rule rule = config.ConfigurationRules.FirstOrDefault(x => x.SequenceNumber == ruleNumber);
                        if (rule != null)
                        {
                            ShowEditRuleForm(rule);
                        }
                    }
                }
                else if (e.CommandName == "DeleteRule")
                {
                    var config = SavedSecurityConfiguration;
                    if (config != null && config.ConfigurationRules != null)
                    {
                        Rule rule = config.ConfigurationRules.FirstOrDefault(x => x.SequenceNumber == ruleNumber);
                        if (rule != null)
                        {
                            config.ConfigurationRules.Remove(rule);
                        }
                        var rules = from r in config.ConfigurationRules
                                    orderby r.SequenceNumber descending
                                    select r;
                        int i = 1;
                        foreach (Rule r in rules)
                        {
                            r.SequenceNumber = i;
                            i++;
                        }
                        SavedSecurityConfiguration = config;
                        ShowExistingRulesForContentType();
                        RuleSequenceNumberTextBox.Text = (config.ConfigurationRules.Count + 1).ToString();
                    }
                }
            }
            catch (Exception ex)
            {
                SetMessage(ex.Message + Environment.NewLine + ex.StackTrace, true);
            }
        }

        protected void AppliedPermissionsGridView_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            try
            {
                int ruleNumber = Convert.ToInt32(e.CommandArgument) + 1;
                if (e.CommandName == "EditRule")
                {
                    var config = SavedSecurityConfiguration;
                    if (config != null && config.ConfigurationRules != null)
                    {
                        Rule rule = config.ConfigurationRules.FirstOrDefault(x => x.SequenceNumber == ruleNumber);
                        if (rule != null)
                        {
                            ShowEditRuleForm(rule);
                        }
                    }
                }
                else if (e.CommandName == "DeleteRule")
                {
                    var config = SavedSecurityConfiguration;
                    if (config != null && config.ConfigurationRules != null)
                    {
                        Rule rule = config.ConfigurationRules.FirstOrDefault(x => x.SequenceNumber == ruleNumber);
                        if (rule != null)
                        {
                            config.ConfigurationRules.Remove(rule);
                        }
                        var rules = from r in config.ConfigurationRules
                                    orderby r.SequenceNumber descending
                                    select r;
                        int i = 1;
                        foreach (Rule r in rules)
                        {
                            r.SequenceNumber = i;
                            i++;
                        }
                        SavedSecurityConfiguration = config;
                        ShowExistingRulesForContentType();
                        RuleSequenceNumberTextBox.Text = (config.ConfigurationRules.Count + 1).ToString();
                    }
                }
            }
            catch (Exception ex)
            {
                SetMessage(ex.Message + Environment.NewLine + ex.StackTrace, true);
            }
        }


        private void ShowEditRuleForm(Rule rule)
        {
            if (rule != null)
            {
                RuleSequenceNumberTextBox.Text = rule.SequenceNumber.ToString();
                AddNewRuleSection.Visible = true;
                RuleNameTextBox.Text = rule.Name;
                MetadataColumnList.SelectedIndex = 0;
                OperatorList.SelectedIndex = 0;
                AppliedConditionsGridView.DataSource = rule.Conditions;
                AppliedConditionsGridView.DataBind();
                if (rule.Action != null && rule.Action.GroupPermissions != null
                    && rule.Action.GroupPermissions.Count > 0)
                {
                    StopInheritingPermissionsCheckBox.Checked = rule.Action.StopInheritingPermission;
                    RemoveInheritedPermissionsCheckBox.Checked = rule.Action.RemoveInheritedPermissions;
                    AppliedPermissionsGridView.DataSource = rule.Action.GroupPermissions;
                    AppliedPermissionsGridView.DataBind();
                    UpdateExistingItemsCheckBox.Checked = rule.Action.UpdateExistingItems;
                }
                GroupList.SelectedIndex = 0;
                PermissionLevelList.SelectedIndex = 0;
                StopProcessingIfRuleAppliesCheckBox.Checked = rule.StopIfRuleApplies;
            }
        }

        private void ShowAddNewRuleForm()
        {
            AddNewRuleSection.Visible = true;
            var config = CurrentSecurityConfiguration;
            if (config != null && config.ConfigurationRules != null)
            {
                RuleSequenceNumberTextBox.Text = (config.ConfigurationRules.Count + 1).ToString();
            }
            RuleNameTextBox.Text = string.Empty;
            MetadataColumnList.SelectedIndex = 0;
            OperatorList.SelectedIndex = 0;
            AppliedConditionsGridView.DataSource = null;
            AppliedConditionsGridView.DataBind();
            StopInheritingPermissionsCheckBox.Checked = false;
            RemoveInheritedPermissionsCheckBox.Checked = false;
            AppliedPermissionsGridView.DataSource = null;
            AppliedPermissionsGridView.DataBind();
            GroupList.SelectedIndex = 0;
            PermissionLevelList.SelectedIndex = 0;
            UpdateExistingItemsCheckBox.Checked = false;
            StopProcessingIfRuleAppliesCheckBox.Checked = false;
        }

        #endregion

        #region Private Methods

        private void AddMetadataValueControl()
        {
            MetadataValueDiv.Controls.Clear();
            if (SelectedContentType != null)
            {
                if (!string.IsNullOrEmpty(MetadataColumnList.SelectedValue))
                {
                    SPField selectedColumn = SelectedContentType.Fields[new Guid(MetadataColumnList.SelectedValue)];
                    ControlHelper helper = new ControlHelper();
                    var control = helper.GetControlForType(selectedColumn.Type);
                    MetadataValueDiv.Controls.Add(control);
                }
            }
        }

        //private void InitializeAppliedRulesAndPermissions()
        //{
        //    MetadataSecuirtyConfiguration config = CurrentSecurityConfiguration;
        //    ViewState["MetadataSecurityConfiguration"] = config;
        //    AppliedConditionsDiv.InnerHtml = GetAppliedConditionsString(config);
        //    AppliedPermissionsDiv.InnerHtml = GetAppliedPermissionString(config);
        //    if (config != null && config.ConfigurationRules != null
        //        && config.ConfigurationRules.Count > 0)
        //    {
        //        var rule = config.ConfigurationRules[0];
        //        if (rule.Action != null)
        //        {
        //            StopInheritingPermissionsCheckBox.Checked = rule.Action.StopInheritingPermission;
        //            RemoveInheritedPermissionsCheckBox.Checked = rule.Action.RemoveInheritedPermissions;
        //            UpdateExistingItemsCheckBox.Checked = rule.Action.UpdateExistingItems;
        //        }
        //        else
        //        {
        //            StopInheritingPermissionsCheckBox.Checked = false;
        //            RemoveInheritedPermissionsCheckBox.Checked = false;
        //            UpdateExistingItemsCheckBox.Checked = false;
        //        }
        //    }
        //    else
        //    {
        //        StopInheritingPermissionsCheckBox.Checked = false;
        //        RemoveInheritedPermissionsCheckBox.Checked = false;
        //        UpdateExistingItemsCheckBox.Checked = false;
        //    }
        //}

        private string GetAppliedConditionsString(Rule rule)
        {
            string s = string.Empty;
            if (rule != null && rule.Conditions != null && rule.Conditions.Count > 0)
            {
                foreach (Condition condition in rule.Conditions)
                {
                    s += "<p>[" + condition.MetadataColumnName + "]" + " " + condition.Operator + " \"" + condition.MetadataValue + "\"<input type='button' value='Remove'></input></p>";
                }
            }
            return s;
        }

        private string GetAppliedPermissionString(Rule rule)
        {
            string s = string.Empty;
            if (rule != null && rule.Action != null
                && rule.Action.GroupPermissions != null && rule.Action.GroupPermissions.Count > 0)
            {
                foreach (GroupPermission gp in rule.Action.GroupPermissions)
                {
                    s += "<p>[" + gp.GroupName + "] <====> [" + gp.PermissionLevelName + "] <input type='button' value='Remove'></input></p>";
                }
            }
            return s;
        }

        private void InitializeContentTypeList()
        {
            SPSite site = SPContext.Current.Site;
            var contentTypes = site.RootWeb.ContentTypes;
            if (contentTypes != null && contentTypes.Count > 0)
            {
                ContentTypeList.DataSource = contentTypes;
                ContentTypeList.DataTextField = "Name";
                ContentTypeList.DataValueField = "Id";
                ContentTypeList.DataBind();
                ContentTypeList.Items.Insert(0, new ListItem("Select Content Type...", string.Empty));
            }
        }

        private void SetMessage(string message, bool isError)
        {
            if (isError)
            {
                ErrorMessageLabel.Text = message;
                MessageLabel.Text = string.Empty;
            }
            else
            {
                MessageLabel.Text = message;
                ErrorMessageLabel.Text = string.Empty;
            }
        }

        private void InitializeMetadataColumnList()
        {
            SPContentType selectedContentType = SelectedContentType;
            if (selectedContentType != null)
            {
                var metadataFields = selectedContentType.Fields.Cast<SPField>().Where(x => (x.Type == SPFieldType.Text)
                    || (x.Type == SPFieldType.Boolean) || (x.Type == SPFieldType.Number));
                MetadataColumnList.DataSource = metadataFields;
                MetadataColumnList.DataTextField = "Title";
                MetadataColumnList.DataValueField = "Id";
                MetadataColumnList.DataBind();
                MetadataColumnList.Items.Insert(0, new ListItem("Select Column...", string.Empty));
            }
        }

        private void InitializePermissionLevelsList()
        {
            SPWeb rootWeb = SPContext.Current.Site.RootWeb;
            SPRoleDefinitionCollection roles = rootWeb.RoleDefinitions;
            PermissionLevelList.DataSource = roles;
            PermissionLevelList.DataTextField = "Name";
            PermissionLevelList.DataValueField = "Id";
            PermissionLevelList.DataBind();
            PermissionLevelList.Items.Insert(0, new ListItem("Select Permission...", string.Empty));
        }

        private void InitializeGroupsList()
        {
            SPWeb rootWeb = SPContext.Current.Site.RootWeb;
            SPGroupCollection groups = rootWeb.Groups;
            GroupList.DataSource = groups;
            GroupList.DataTextField = "Name";
            GroupList.DataValueField = "Id";
            GroupList.DataBind();
            GroupList.Items.Insert(0, new ListItem("Select Group...", string.Empty));
        }
        private void RemoveEventReceiverFromContentType(SPContentType contentType)
        {
            if (contentType != null)
            {
                IEnumerable<SPEventReceiverDefinition> eventRecCol = contentType.EventReceivers.Cast<SPEventReceiverDefinition>().Where(x => x.Class == "SPMetadataSecurity.MetadataSecurityEventReceiver");

                if (eventRecCol != null && eventRecCol.Count() > 0)
                {
                    for (int i = 0; i < eventRecCol.Count(); i++)
                    {
                        var eventRec = eventRecCol.ElementAt(i);
                        eventRec.Delete();
                        contentType.Update(true);
                    }
                }
            }
        }

        private void AddEventReceiverToContentType(SPContentType contentType)
        {
            if (contentType != null)
            {
                SPEventReceiverDefinition itemAddedEventReceiver = contentType.EventReceivers.Add();
                itemAddedEventReceiver.Synchronization = SPEventReceiverSynchronization.Synchronous;
                itemAddedEventReceiver.Type = SPEventReceiverType.ItemAdded;
                itemAddedEventReceiver.Assembly = Assembly.GetExecutingAssembly().FullName;
                itemAddedEventReceiver.Class = "SPMetadataSecurity.MetadataSecurityEventReceiver"; // typeof(MetadataSecurityEventReceiver).Name;

                itemAddedEventReceiver.Update();

                SPEventReceiverDefinition itemUpdatedEventReceiver = contentType.EventReceivers.Add();
                itemUpdatedEventReceiver.Synchronization = SPEventReceiverSynchronization.Synchronous;
                itemUpdatedEventReceiver.Type = SPEventReceiverType.ItemUpdated;
                itemUpdatedEventReceiver.Assembly = Assembly.GetExecutingAssembly().FullName;
                itemUpdatedEventReceiver.Class = "SPMetadataSecurity.MetadataSecurityEventReceiver"; // typeof(MetadataSecurityEventReceiver).DeclaringType.FullName;
                itemUpdatedEventReceiver.Update();
                contentType.Update(true);
            }
        }

        #endregion

        
    }
}
